import { Grid } from '@arco-design/web-react';
import { Switch } from 'react-vant';
import { updateCaption } from '@/store/slices/room';
import { useLeave } from '@/lib/useCommon';
import { useNavigate } from 'react-router-dom';
import TimeToast from './timeToast';
import RtcClient from '@/lib/RtcClient';
import TalkTime from '@/assets/AiImgs/timeImg.png'
import { useSelector } from 'react-redux';
import styles from './index.module.less';
import { useState, useEffect, useRef } from 'react'; // 添加 useRef
import { useDispatch } from 'react-redux';
import { callFinished, setAutoHangup } from '@/store/slices/room';

const Row = Grid.Row;
const Col = Grid.Col;

interface HeaderProps {
  children?: React.ReactNode;
  hide?: boolean;
  show?: string;
}

function Header(props: HeaderProps) {
  const { children, hide, show } = props;
  const dispatch = useDispatch();
  const room = useSelector((state: any) => state.room);
  const isJoined = room.isJoined || show === 'isjoined';
  const isFinished = room.isFinished;
  const [callDuration, setCallDuration] = useState(0);
  const [showTip, setShowTip] = useState(false);
  const [durationCount, setDurationCount] = useState(0);
  const [isCountdownActive, setIsCountdownActive] = useState(false);
  const navigate = useNavigate();
  const leaveRoom = useLeave();
  
  // 使用 useRef 存储计时器 ID
  const timerRef = useRef<NodeJS.Timeout | null>(null);
  
  // 跟踪计时器是否已经启动
  const timerStartedRef = useRef(false);

  const onLeaveRoom = async () => {
    dispatch(callFinished({ data: true }));
    let prcid = RtcClient.getPracticeId();
    let res = await leaveRoom();
    if (res.code === 2000) {
      setIsCountdownActive(false);
      setShowTip(false);
      dispatch(setAutoHangup({ data: false }));
      navigate(`/TrainingEnd?prcid=${prcid}`, { replace: false });
    }
  };

  // 清除计时器
  const clearTimer = () => {
    if (timerRef.current) {
      clearInterval(timerRef.current);
      timerRef.current = null;
    }
  };

  // 启动计时器
  const startTimer = () => {
    if (timerRef.current) return; // 避免重复启动
    
    console.log('启动计时器');
    timerRef.current = setInterval(() => {
      setCallDuration(prev => prev + 1);
    }, 1000);
    timerStartedRef.current = true;
  };

  // 主要计时器逻辑 - 重新编写，不再依赖 isFinished
  useEffect(() => {
    // 当房间加入或训练开始时启动计时器
    if ((room.isJoined || room.isStart) && !timerStartedRef.current) {
      clearTimer(); // 确保清除任何可能的残留计时器
      startTimer();
    }
    
    // 当房间离开或训练结束时停止计时器
    if ((!room.isJoined && !room.isStart) && timerStartedRef.current) {
      console.log('停止计时器');
      clearTimer();
      timerStartedRef.current = false;
    }
    
    // 清理函数
    return () => {
      console.log('清理效果');
      clearTimer();
    };
  }, [room.isJoined, room.isStart]); // 只依赖房间状态

  // 重置时间
  useEffect(() => {
    if (room.timeReset) {
      console.log('重置时间');
      setCallDuration(0);
      setIsCountdownActive(false);
      setShowTip(false);
      
      // 重新启动计时器
      clearTimer();
      if (room.isJoined || room.isStart) {
        startTimer();
      }
    }
  }, [room.timeReset]);

  // 剩余时间逻辑
  useEffect(() => {
    if (room.trainDuration) {
      const toSecond = room.trainDuration * 60;
      const count = toSecond - callDuration;

      // 30秒提示（只显示一次）
      if (count === 30 && !isCountdownActive) {
        console.log('30秒提示');
        setDurationCount(30);
        setShowTip(true);
        setTimeout(() => setShowTip(false), 3000);
      }
      // 10秒开始持续显示倒计时
      else if (count <= 10 && count > 0) {
        console.log('10秒倒计时开始');
        setIsCountdownActive(true);
        setDurationCount(count);
        setShowTip(true);
      }
      // 0秒自动挂断
      else if (count === 0) {
        console.log('自动挂断');
        onLeaveRoom();
      }
    }
  }, [callDuration, room.trainDuration]);

  // 处理组件卸载
  useEffect(() => {
    return () => {
      console.log('组件卸载');
      dispatch(callFinished({ data: true }));
      setIsCountdownActive(false);
      setShowTip(false);
      dispatch(setAutoHangup({ data: false }));
      clearTimer(); // 确保清除计时器
      dispatch(updateCaption({ data: true }));
    };
  }, []);

  // 格式化时间显示
  const formatTime = (seconds: number) => {
    const h = Math.floor(seconds / 3600);
    const m = Math.floor((seconds % 3600) / 60);
    const s = seconds % 60;
    return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
  };

  const onSwitchChange = (e: boolean) => {
    dispatch(updateCaption({ data: e }));
  };

  return (
    <>
      {/* 倒计时模式 */}
      {isCountdownActive && (
        <TimeToast duration={durationCount} />
      )}
      
      {/* 正常模式 */}
      {!isCountdownActive && (isJoined || show === 'isstudy') && (
        <div className={`${styles.mobileHeader} bg-[#222222]`}>
          <Row className="text-[#999999] font-normal" align="center">
            <Col span={8} className="pl-5 text-[10px]">普通话</Col>
            <Col span={8} className="font-bold text-center flex items-center justify-center">
              <img 
                style={{ width: '26px', height: '10px' }} 
                className="mr-2.5" 
                src={TalkTime} 
                alt="Time icon" 
              />
              {formatTime(callDuration)}
              <img 
                style={{ width: '26px', height: '10px' }} 
                className="ml-2.5" 
                src={TalkTime} 
                alt="Time icon" 
              />
            </Col>
            <Col span={8} className="text-right pr-5 text-[10px] flex justify-end items-center">
              {isJoined && (
                <Switch 
                  activeColor="#FFBC0D" 
                  inactiveColor="#cccccc" 
                  size="22px" 
                  defaultChecked 
                  onChange={onSwitchChange} 
                  className="ml-1.5"
                />
              )}
            </Col>
          </Row>
        </div>
      )}
      
      {/* 提示框 */}
      {showTip && !isCountdownActive && <TimeToast duration={durationCount} />}
    </>
  );
}

export default Header;